package utils

import (
	"bytes"
	"github.com/BurntSushi/graphics-go/graphics"
	"github.com/skip2/go-qrcode"
	"image"
	"image/draw"
	_ "image/jpeg"
	"image/png"
)

func scaleLogoImg(img image.Image, size int) (out image.Image, err error) {
	dst := image.NewRGBA(image.Rect(0, 0, size, size))
	err = graphics.Scale(dst, img)
	return dst, err
}

/*
NewQrcode 生成二维码，带logo
默认生成长宽为 512 像素的 二维码图片
logo 自动缩放为 128 像素
如需加入圆角矩形 Logo 务必设计一张 白色底色的logo，其圆角边应透明
*/
func NewQrcode(u string, logo []byte) (out []byte, err error) {
	logoimg, _, err := image.Decode(bytes.NewReader(logo))
	if err != nil {
		return
	}

	logoimg, err = scaleLogoImg(logoimg, 128)
	if err != nil {
		return
	}

	body, err := qrcode.Encode(u, qrcode.Highest, 512)
	img, _, err := image.Decode(bytes.NewReader(body))
	if err != nil {
		return
	}

	A, B := img.Bounds().Max.X, img.Bounds().Max.Y
	a, b := logoimg.Bounds().Max.X, logoimg.Bounds().Max.Y
	r := image.Rectangle{
		Min: image.Point{
			X: A/2 - a/2,
			Y: B/2 - b/2,
		},
		Max: image.Point{
			X: A/2 + a/2,
			Y: B/2 + b/2,
		},
	}
	dst := image.NewRGBA(img.Bounds())
	// 先写入第一张图
	draw.Draw(dst, dst.Bounds(), img, image.ZP, draw.Over)
	// 再覆盖上logo
	draw.Draw(dst, r, logoimg, image.ZP, draw.Over)

	var buf bytes.Buffer
	err = png.Encode(&buf, dst)
	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}
